package com.hivis.websocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

@Component("mywebsockethandler")
public class MyWebSocketHandler implements WebSocketHandler {

	private final static Logger sysLogger = LoggerFactory.getLogger("system");
	
	// 在线平板Map<设备序列号, session>
	public static final Map<String, WebSocketSession> notebookSessionMap = new ConcurrentHashMap<String, WebSocketSession>();

	@Resource(name = "taskExecutor")
    TaskExecutor myThreadPool;

	public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
		System.out.println("Websocket:" + session.getId() + "已经关闭");
		notebookSessionMap.remove(session.getId());
	}

	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
//		String token = (String) session.getAttributes().get("token");
//		String userId = TokenUtil.getClaimValue(token, "userId");
//		System.out.println("uerId------->" + UserUtils.getUser().getId());
		String notebookId =  (String) session.getAttributes().get("notebookId");
		if(StringUtils.isNotEmpty(notebookId)){
			notebookSessionMap.put(notebookId, session);
		}
	}

	public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
		session.sendMessage(message);
		JSONObject jsonObject = JSON.parseObject(message.getPayload().toString());
		System.out.println("------------------>" + jsonObject);
	}

	public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
		if (session.isOpen()) {
			session.close();
		}
		Iterator<Entry<String, WebSocketSession>> it = notebookSessionMap.entrySet().iterator();
		// 移除Socket会话
		while (it.hasNext()) {
			Entry<String, WebSocketSession> entry = it.next();
			if (entry.getValue().getId().equals(session.getId())) {
				notebookSessionMap.remove(entry.getKey());
				System.out.println("Socket会话已经移除:用户ID" + entry.getKey());
				break;
			}
		}

	}

	public boolean supportsPartialMessages() {
		// TODO Auto-generated method stub
		return false;
	}

	/**
	 * 群发
	 * 
	 * @param message
	 * @throws IOException
	 */
	public void broadcast(final TextMessage message) throws IOException {
		System.out.println("进入broadcast");
		Iterator<Entry<String, WebSocketSession>> it = notebookSessionMap.entrySet().iterator();

		// 多线程群发
		while (it.hasNext()) {
			System.out.println("多线程群发");
			final Entry<String, WebSocketSession> entry = it.next();
			final WebSocketSession webSocketSession = entry.getValue();
			if (webSocketSession.isOpen()) {
				// 线程池+同步块
				myThreadPool.execute(new Runnable() {
					public void run() {
						Thread.currentThread().setName("Thread-broadcast");
						// 通知客户端
						sendMessage(webSocketSession, message);
					}
				});
			}
		}
	}

	/**
	 * 向用户推送消息
	 * @param message 推送的消息
	 * @param c 接受消息的用户列表
	 * @throws IOException
	 */
	public void sendMessageToBrower(final TextMessage message, List<?> c) throws IOException {

//		for(Object it : c){
//			String id = null;
//			if(it instanceof User){
//				id = ((User) it).getId();
//			}else if(it instanceof String){
//				id = (String)it;
//			}
//			final String userId = id;
//			if(userSocketSessionMap.containsKey(id)){
//				// 线程池+同步块
//				myThreadPool.execute(new Runnable() {
//					@Override
//					public void run() {
//						Thread.currentThread().setName("Thread-sendMessageToBrower");
//						WebSocketSession webSocketSession = userSocketSessionMap.get(userId);
//
//						sendMessage(webSocketSession, message);
//					}
//				});
//			}
//		}
	}
	public void sendMessage(String  notebookeId, TextMessage message){
		WebSocketSession webSocketSession = notebookSessionMap.get(notebookeId);
		sendMessage(webSocketSession, message);
	}
	
	public void sendMessage(WebSocketSession webSocketSession, TextMessage message){
		if (webSocketSession != null && webSocketSession.isOpen()) {
			synchronized(webSocketSession){
				try {
					webSocketSession.sendMessage(message);
				} catch (IOException e) {
					sysLogger.error(e.getMessage(), e);
				}
			}
		}
	}

	public  void sendMessage(String  notebookeId, BinaryMessage message){
		WebSocketSession webSocketSession = notebookSessionMap.get(notebookeId);
		sendMessage(webSocketSession, message);
	}

	public  void sendMessage(WebSocketSession webSocketSession, BinaryMessage message){
		if (webSocketSession != null && webSocketSession.isOpen()) {
			synchronized(webSocketSession){
				try {
					webSocketSession.sendMessage(message);
				} catch (IOException e) {
					sysLogger.error(e.getMessage(), e);
				}
			}
		}
	}
}
